package cn.com.tiza.spiro.jvm.gc.optimization;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by TZ0643 on 2016-1-6.
 */
public class HelloServlet extends HttpServlet {

    private static final int _1M = 1024 * 1024;

    private static final Map<String, Integer> sessionMap = new ConcurrentHashMap<String, Integer>();
    private static final List<byte[]> alloc = Collections.synchronizedList(new ArrayList<byte[]>());

    static {
        Thread thd = new Thread() {
            @Override
            public void run() {

                while(true) {
                    if(alloc.size() > 100) {
                        alloc.clear();
                    }
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                }
            }
        };
        thd.setDaemon(true);
        thd.start();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        alloc.add(new byte[_1M]);

        HttpSession session = req.getSession();
        String id = null;
        if(session != null) {
            id = session.getId();
        }

        if(id != null) {
            Integer i = sessionMap.get(id);
            if(i == null) {
                i = 0;
            }
            sessionMap.put(id, ++i);
        }

        PrintWriter out = resp.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("</head>");
        out.println("<body>");
        out.println("<table border='1' cellspace='0' >");
        Set<Map.Entry<String, Integer>> entrySet = sessionMap.entrySet();
        for (Map.Entry<String, Integer> entry: entrySet) {
            out.print("<tr>");
            out.print("<td>");
            out.print(entry.getKey());
            out.print("</td>");
            out.print("<td>");
            out.print(entry.getValue());
            out.print("</td>");
            out.println("</tr>");
        }

        out.println("</table>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
